package com.xh.new_im_start;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.COE.MdmSdkLib.API;
import com.COE.MdmSdkLib.AUTO_SEND_RECORD_DATA;
import com.COE.MdmSdkLib.DeviceInfo;
import com.COE.MdmSdkLib.SdkLibListener;
import com.COE.MdmSdkLib.SdkLibManager;

public class MainActivity extends AppCompatActivity implements  SdkLibListener , View.OnClickListener{

    protected static final String ACTIVITY_TAG="COE_SDK";

    private Button mBtn_init;
    private Button mBtn_senddata;
    private Button mBtn_active_offline;
    private TextView mText_recv_msg;
    private EditText mEditText;

    private int mCMD;
    private String mSender_imid;
    private String mTarget_imid;
    private String mPb;

    private SdkLibManager sd;

    static  public boolean issuc = true;
    static  public boolean bisbegin = true;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                mText_recv_msg.setText("CMD = " + mCMD + "\n"
                        + "sender_imid = " + mSender_imid + "\n"
                        + "target_imid = " + mTarget_imid + "\n"
                        + "pb = " + mPb);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        onInitView();
        onInitData();
    }

    private void onInitView() {
        mBtn_init = (Button) findViewById(R.id.btn_init);
        mBtn_senddata = (Button) findViewById(R.id.btn_senddata);
        mBtn_active_offline = (Button) findViewById(R.id.btn_active_offline);
        mText_recv_msg = (TextView) findViewById(R.id.text_recv_msg);
        mEditText = (EditText) findViewById(R.id.edit_text);

        mBtn_init.setOnClickListener(this);
        mBtn_senddata.setOnClickListener(this);
        mBtn_active_offline.setOnClickListener(this);
    }

    private void onInitData() {
        sd = SdkLibManager.getInstance();
        sd.set__sdklib_Listener(MainActivity.this);
    }

    //单聊接收消息
    @Override
    public void OnBaseImProcessNotity(int cmd, byte[] sender_imid, byte[] target_imid, byte[] pb, int len) {
        // TODO Auto-generated method stub
        String str_send = new String(sender_imid);
        String str_target = new String(target_imid);
        String str_pb = new String(pb);

        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotity************** sender_imid:" + str_send);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotity************** target_imid:" + str_target);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotity************** CMD:" + cmd);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotity************** pb:" + str_pb);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotity************** len:" + len);

        mCMD = cmd;
        mSender_imid = str_send;
        mTarget_imid = str_target;
        mPb = str_pb;

        mHandler.sendEmptyMessage(0);
    }

    //群聊接收消息
    @Override
    public void OnBaseImProcessNotifyByGroup(int cmd, byte[] sender_imid, byte[] group_id, byte[] pb, int len) {
        String str_send = new String(sender_imid);
        String str_group = new String(group_id);
        String str_pb = new String(pb);

        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByGroup************** sender_imid:" + str_send);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByGroup************** target_imid:" + str_group);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByGroup************** CMD:" + cmd);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByGroup************** pb:" + str_pb);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByGroup************** len:" + len);
    }

    //公众号
    @Override
    public void OnBaseImProcessNotifyByPublicAcc(int cmd, byte[] sender_imid, byte[] target_imid, byte[] pb, int len) {
        String str_send = new String(sender_imid);
        String str_target = new String(target_imid);
        String str_pb = new String(pb);

        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByPublicAcc************** sender_imid:" + str_send);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByPublicAcc************** target_imid:" + str_target);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByPublicAcc************** CMD:" + cmd);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByPublicAcc************** pb:" + str_pb);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByPublicAcc************** len:" + len);
    }

    @Override
    public void OnBaseImProcessNotifyBySync(int cmd, byte[] sender_imid, byte[] target_imid, byte[] pb, int len) {
        String str_send = new String(sender_imid);
        String str_target = new String(target_imid);
        String str_pb = new String(pb);

        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyBySyc************** sender_imid:" + str_send);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyBySyc************** target_imid:" + str_target);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifySyc************** CMD:" + cmd);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifySyc************** pb:" + str_pb);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifySyc************** len:" + len);
    }

    //通知接收消息
    @Override
    public void OnBaseImProcessNotifyByNotice(int cmd, byte[] sender_imid, byte[] target_imid, byte[] pb, int len) {
        String str_send = new String(sender_imid);
        String str_target = new String(target_imid);
        String str_pb = new String(pb);

        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByNotice************** sender_imid:" + str_send);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByNotice************** target_imid:" + str_target);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByNotice************** CMD:" + cmd);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByNotice************** pb:" + str_pb);
        Log.e(ACTIVITY_TAG, "[COE]OnBaseImProcessNotifyByNotice************** len:" + len);
    }


    // 当sdk出现异常时, 回调安卓
    @Override
    public void OnImErrorNotify(int val) {
        //TODO 异常时, C回调这个函数, 并返回ERROR CODE 到 val
        System.out.println("[COE] OnImErrorNotify : val = " + val);
        sd = SdkLibManager.getInstance();
//        if (101 == val && isfirst == 0) {
//            isfirst ++;
//            while (true) {
//                Log.e(ACTIVITY_TAG, "[INFO][ANDROID] isfirst: " + isfirst);
//                try {
//                    Thread.sleep(5000);//1000ms = 1sec
//                    System.out.println("[COE] OnImErrorNotify :  This is sleep");
//                    Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is Re Init!");
//                    DeviceInfo dv = new DeviceInfo();
//                    int ret = sd.init("192.168.43.178", 8888, dv);
//
////                    //int ret = sd.init("172.29.3.42", 8888);
////                    //int ret = sd.init("192.168.77.46", 8888);
//                   if (0 == ret) {
//                        Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : init sdklib ok!!!!!!!!!!!!!!!!!!!");
//                       isfirst = 0;
//                        return;
//                    } else {
//                        Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : init sdklib fail!!!!!!!!!!!!!!!!!!!");
//                    }
//
//                } catch (InterruptedException e) {
//                }
//
//            }
//        } else if (102 == val) {
//            System.out.println("[COE] OnImErrorNotify : val =================== " + val);
//        }
        if (101 == val) {
            issuc = false;
        } else if (100 == val) {
            System.out.println("[COE] OnImErrorNotify : val =================== " + val);
            issuc = true;
            String bb = "12345";
            sd.sendimstrdata(1001, "tan", "mainservice", bb.getBytes());
        }

    }

    public void OnReinit(){
        while(true){
            Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is sleep OnReinit!");
            try {
                Thread.sleep(5000);//1000ms = 1sec
                if(!issuc) {
                    Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is Re Init!");
                    DeviceInfo dv = new DeviceInfo();
                    int ret = sd.init("20.97.6.158", 7006, dv);
                    if (0 == ret) {
                        Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : init sdklib ok!!!!!!!!!!!!!!!!!!!");
                        issuc = true;
                    } else {
                        Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : init sdklib fail!!!!!!!!!!!!!!!!!!!");
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void OnSdkInitResultNotify(int val) {
        if (val == 0) {
            Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : OnSdkInitResultNotify  ok!");
        } else if (val == -1) {
            Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : OnSdkInitResultNotify  failed!");
        }
    }

    void initSdk() {
        Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is Init!");

        //下面的参数设置 C-server 的 ip和port，而imid的设置在这个函数里面.请自己调整和封装即可
        DeviceInfo dv = new DeviceInfo();
        //int ret = sd.init("222.85.229.55", 20013, dv);
        int ret = sd.init("20.97.6.158" , 7006, dv);
        //int ret = sd.init("10.248.97.236" , 7006, dv);
        if (bisbegin) {
            Thread t = new Thread(new Runnable() {
                public void run() {
                    // run方法具体重写
                    OnReinit();
                }
            });
            t.start();
            bisbegin = false;
        }
        //int ret = sd.init("172.29.3.42", 8888);
        //int ret = sd.init("20.97.6.62", 8888, dv);
        if (0 == ret)
        {
            Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : init sdklib ok!!!!!!!!!!!!!!!!!!!");
        }
        else
        {
            Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : init sdklib fail!!!!!!!!!!!!!!!!!!!");
        }
    }

    void sendData() {
        Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is android SendData!");
        //String s = "helloworldhelloworldhelloworldhelloworldhelloworldhelloworld";
        String s = mEditText.getText().toString();
        byte b[] = s.getBytes();

        //由于imid改为string类型,所以发送也要改
        sd.sendimstrdata(2041, "long_yc", "mainservice", b);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_init:
                initSdk();
                break;
            case R.id.btn_senddata:
                try {
                    sendData();
                } catch (Exception e) {
                    Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is try catch !!!!!!!!!!!");
                    Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is try catch !!!!!!!!!!!");
                    Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is try catch !!!!!!!!!!!");
                    Log.e(ACTIVITY_TAG, "[INFO][ANDROID] : This is try catch !!!!!!!!!!!");
                }
                break;
            case R.id.btn_active_offline:
                API.ActiveOffLine();
                break;
        }
    }



    //////////////////////////////////////////////////////
    @Override
    public void OnReceiveCmd(int handler, int task_no, String json) {
        // TODO Auto-generated method stub

    }

    @Override
    public void OnReceiveCmdResult(int handler, int task_no, int result) {
        // TODO Auto-generated method stub

    }

    @Override
    public void OnReceiveNotify(int handler, String json) {
        // TODO Auto-generated method stub

    }

    @Override
    public void OnLogFunc(int level, String module, int line, String message) {
        // TODO Auto-generated method stub
        if (level >= SDK_DEBUG_LEVEL) {
            System.out.println("module:" + module + " Line:" + line + " Message:" + message);
        }
    }

    @Override
    public void OnLoginComplete(int errcode) {
        // TODO Auto-generated method stub

    }

    @Override
    public void OnOnlineStatus(int old, int new_status) {
        // TODO Auto-generated method stub

    }

    @Override
    public String AutoSendStatus() {
        // TODO Auto-generated method stub
        String data = "";
        return data;
    }

    /*
     * Json数据是这样的。多个Topic时，则组成Json数组。
    {
        “topic_count”:4// 采集的数据点数量。
        "data": [  // 实际需要采集哪些topic
                {
                “time”:”1791111111111” //时间
                “topic”:”data_point_1”  //需要采集的数据点名称
                "data": “数据值”   // 采集的数据的值
                }
                {
                “time”:”1791111111111” //时间
                “topic”:”data_point_2”  //需要采集的数据点名称
                "data": “数据值”   // 采集的数据的值
                }
            ]
        }
     */
    @Override
    public AUTO_SEND_RECORD_DATA AutoSendRecord(int handler) {
        // TODO Auto-generated method stub
        AUTO_SEND_RECORD_DATA data = new AUTO_SEND_RECORD_DATA();
        data.record_type = 1;
        data.priority = 0;
        data.qos = 0;
        data.json = "我是一个Json数据,具体格式见注释里的实例";
        return data;
    }
}
